namespace DotNetNuke.Entities.Modules
{
    using DotNetNuke.Common;
    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities.Modules.Actions;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Entities.Users;
    using DotNetNuke.Security;
    using DotNetNuke.Security.Permissions;
    using Microsoft.VisualBasic;
    using Microsoft.VisualBasic.CompilerServices;
    using System;
    using System.Collections;
    using System.ComponentModel;
    using System.IO;
    using System.Runtime.CompilerServices;
    using System.Threading;
    using System.Web;
    using System.Web.UI;

    /// -----------------------------------------------------------------------------
    /// Project	 : DotNetNuke
    /// Class	 : PortalModuleBase
    /// 
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The PortalModuleBase class defines a custom base class inherited by all
    /// desktop portal modules within the Portal.
    /// 
    /// The PortalModuleBase class defines portal specific properties
    /// that are used by the portal framework to correctly display portal modules
    /// </summary>
    /// <remarks>
    /// </remarks>
    /// <history>
    /// [cnurse]	09/17/2004	Added Documentation
    /// Modified LocalResourceFile to be Writeable
    /// [cnurse]	10/21/2004	Modified Settings property to get both
    /// TabModuleSettings and ModuleSettings
    /// </history>
    /// -----------------------------------------------------------------------------
    public class PortalModuleBase : UserControl
    {
        private ModuleActionCollection _actions;
        private string _cachedOutput = "";
        private string _helpfile;
        private string _helpurl;
        private int _isEditable = 0;
        private string _localResourceFile;
        private ModuleInfo _moduleConfiguration;
        private Hashtable _settings;

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The CreateChildControls method is called when the ASP.NET Page Framework
        /// determines that it is time to instantiate a server control.
        /// This method and attempts to resolve any previously cached output of the portal 
        /// module from the ASP.NET cache.  
        /// If it doesn't find cached output from a previous request, then it will instantiate 
        /// and add the portal modules UserControl instance into the page tree.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 17/9/2004  Added Documentation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void CreateChildControls()
        {
            if ((this._moduleConfiguration != null) && (!PortalSecurity.IsInRole(this.PortalSettings.AdministratorRoleName.ToString()) & !PortalSecurity.IsInRoles(this.PortalSettings.ActiveTab.AdministratorRoles.ToString())))
            {
                if (this._moduleConfiguration.CacheTime != 0)
                {
                    if (this.CacheMethod != "D")
                    {
                        this._cachedOutput = Convert.ToString(RuntimeHelpers.GetObjectValue(DataCache.GetCache(this.CacheKey)));
                    }
                    else if (File.Exists(this.CacheFileName))
                    {
                        FileInfo cacheFile = new FileInfo(this.CacheFileName);
                        if (DateTime.Compare(cacheFile.CreationTime.AddSeconds((double) this._moduleConfiguration.CacheTime), DateAndTime.Now) >= 0)
                        {
                            StreamReader objStreamReader = cacheFile.OpenText();
                            this._cachedOutput = objStreamReader.ReadToEnd();
                            objStreamReader.Close();
                        }
                        else
                        {
                            cacheFile.Delete();
                        }
                    }
                }
                if ((this._cachedOutput == "") & (this._moduleConfiguration.CacheTime > 0))
                {
                    base.CreateChildControls();
                    PortalModuleBase objPortalModuleBase = (PortalModuleBase) this.Page.LoadControl(this._moduleConfiguration.ControlSrc);
                    objPortalModuleBase.ModuleConfiguration = this.ModuleConfiguration;
                    objPortalModuleBase.ModuleConfiguration.CacheTime = 0 - objPortalModuleBase.ModuleConfiguration.CacheTime;
                    this.Controls.Add(objPortalModuleBase);
                }
                else if (this._moduleConfiguration.CacheTime < 0)
                {
                    this._moduleConfiguration.CacheTime = 0 - this._moduleConfiguration.CacheTime;
                }
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public string EditUrl()
        {
            return this.EditUrl("", "", "Edit");
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public string EditUrl(string ControlKey)
        {
            return this.EditUrl("", "", ControlKey);
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string EditUrl(string KeyName, string KeyValue)
        {
            return this.EditUrl(KeyName, KeyValue, "Edit");
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public string EditUrl(string KeyName, string KeyValue, string ControlKey)
        {
            string key = ControlKey;
            if (key == "")
            {
                key = "Edit";
            }
            if ((KeyName != "") & (KeyValue != ""))
            {
                return DotNetNuke.Common.Globals.NavigateURL(this.PortalSettings.ActiveTab.TabID, key, new string[] { "mid=" + this.ModuleId.ToString(), KeyName + "=" + KeyValue });
            }
            return DotNetNuke.Common.Globals.NavigateURL(this.PortalSettings.ActiveTab.TabID, key, new string[] { "mid=" + this.ModuleId.ToString() });
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string EditUrl(string KeyName, string KeyValue, string ControlKey, params string[] AdditionalParameters)
        {
            string key = ControlKey;
            if (key == "")
            {
                key = "Edit";
            }
            string[] localParams;
            if ((KeyName != "") & (KeyValue != ""))
            {
                localParams = new string[(AdditionalParameters.Length + 1) + 1];
                localParams[0] = "mid=" + this.ModuleId.ToString();
                localParams[1] = KeyName + "=" + KeyValue;
                int refIntHelperL1 = AdditionalParameters.Length - 1;
                for (int i = 0; i <= refIntHelperL1; i++)
                {
                    localParams[i + 2] = AdditionalParameters[i];
                }
                return DotNetNuke.Common.Globals.NavigateURL(this.PortalSettings.ActiveTab.TabID, key, localParams);
            }
            localParams = new string[AdditionalParameters.Length + 1];
            localParams[0] = "mid=" + this.ModuleId.ToString();
            int refIntHelperL2 = AdditionalParameters.Length - 1;
            for (int i = 0; i <= refIntHelperL2; i++)
            {
                localParams[i + 1] = AdditionalParameters[i];
            }
            return DotNetNuke.Common.Globals.NavigateURL(this.PortalSettings.ActiveTab.TabID, key, localParams);
        }

        protected int GetNextActionID()
        {
            return (this.Actions.Count + 1);
        }

        public bool HasModulePermission(string PermissionKey)
        {
            return ModulePermissionController.HasModulePermission(this.ModuleConfiguration.ModulePermissions, PermissionKey);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Render method is called when the ASP.NET Page Framework
        /// determines that it is time to render content into the page output stream.
        /// This method and captures the output generated by the portal module user control
        /// It then adds this content into the ASP.NET Cache for future requests.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 17/9/2004  Added Documentation
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void Render(HtmlTextWriter output)
        {
            if (this._moduleConfiguration != null)
            {
                if ((this._moduleConfiguration.CacheTime == 0) | (PortalSecurity.IsInRoles(this.PortalSettings.AdministratorRoleName) | PortalSecurity.IsInRoles(this.PortalSettings.ActiveTab.AdministratorRoles.ToString())))
                {
                    base.Render(output);
                }
                else
                {
                    if (this._cachedOutput == "")
                    {
                        StringWriter tempWriter = new StringWriter();
                        base.Render(new HtmlTextWriter(tempWriter));
                        this._cachedOutput = tempWriter.ToString();
                        if (this.CacheMethod != "D")
                        {
                            DataCache.SetCache(this.CacheKey, this._cachedOutput, DateTime.Now.AddSeconds((double) this._moduleConfiguration.CacheTime));
                        }
                        else
                        {
                            try
                            {
                                if (!Directory.Exists(this.CacheDirectory))
                                {
                                    Directory.CreateDirectory(this.CacheDirectory);
                                }
                                StreamWriter objStream = File.CreateText(this.CacheFileName);
                                objStream.WriteLine(this._cachedOutput);
                                objStream.Close();
                            }
                            catch (Exception exception1)
                            {
                                
                                
                            }
                        }
                    }
                    output.Write(this._cachedOutput);
                }
            }
            else
            {
                base.Render(output);
            }
        }

        public void SynchronizeModule()
        {
            if (this.CacheMethod != "D")
            {
                DataCache.RemoveCache(this.CacheKey);
            }
            else if (File.Exists(this.CacheFileName))
            {
                try
                {
                    File.Delete(this.CacheFileName);
                }
                catch (Exception exception1)
                {
                    
                    
                }
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public ModuleActionCollection Actions
        {
            get
            {
                if (this._actions == null)
                {
                    this._actions = new ModuleActionCollection();
                }
                return this._actions;
            }
            set
            {
                this._actions = value;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The CacheDirectory property is used to return the location of the "Cache"
        /// Directory for the Module
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 04/28/2005  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string CacheDirectory
        {
            get
            {
                return (this.PortalSettings.HomeDirectoryMapPath + "Cache");
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The CacheFileName property is used to store the FileName for this Module's
        /// Cache
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 04/28/2005  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string CacheFileName
        {
            get
            {
                return (this.CacheDirectory + @"\" + DotNetNuke.Common.Globals.CleanFileName(this.CacheKey) + ".htm");
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The CacheKey property is used to calculate a "unique" cache key
        /// entry to be used to store/retrieve the portal module's content
        /// from the ASP.NET Cache. Note that cache key allows two versions of the module
        /// content to be stored - one for anonymous and one for authenticated users.
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 17/9/2004  Added Documentation
        /// </history>
        /// -----------------------------------------------------------------------------
        public string CacheKey
        {
            get
            {
                string strCacheKey = "TabModule:";
                return ((strCacheKey + this.TabModuleId.ToString() + ":") + Thread.CurrentThread.CurrentCulture.ToString());
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The CacheMethod property is used to store the Method used for this Module's
        /// Cache
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <history>
        /// [cnurse] 04/28/2005  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        public string CacheMethod
        {
            get
            {
                return Convert.ToString(RuntimeHelpers.GetObjectValue(DotNetNuke.Common.Globals.HostSettings["ModuleCaching"]));
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public Control ContainerControl
        {
            get
            {
                return DotNetNuke.Common.Globals.FindControlRecursive(this, "ctr" + this.ModuleId.ToString());
            }
        }

        [Obsolete("The HelpFile() property was deprecated in version 2.2. Help files are now stored in the /App_LocalResources folder beneath the module with the following resource key naming convention: ModuleHelp.Text")]
        public string HelpFile
        {
            get
            {
                return this._helpfile;
            }
            set
            {
                this._helpfile = value;
            }
        }

        public string HelpURL
        {
            get
            {
                return this._helpurl;
            }
            set
            {
                this._helpurl = value;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public bool IsEditable
        {
            get
            {
                if (this._isEditable == 0)
                {
                    bool blnPreview = false;
                    if (this.Request.Cookies["_Tab_Admin_Preview" + this.PortalId.ToString()] != null)
                    {
                        blnPreview = bool.Parse(this.Request.Cookies["_Tab_Admin_Preview" + this.PortalId.ToString()].Value);
                    }
                    if ((this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.AdminTabId) | (this.PortalSettings.ActiveTab.ParentId == this.PortalSettings.SuperTabId))
                    {
                        blnPreview = false;
                    }
                    bool blnHasModuleEditPermissions = (PortalSecurity.IsInRoles(this._moduleConfiguration.AuthorizedEditRoles) | PortalSecurity.IsInRoles(this.PortalSettings.ActiveTab.AdministratorRoles)) | PortalSecurity.IsInRoles(this.PortalSettings.AdministratorRoleName);
                    if (!blnPreview & blnHasModuleEditPermissions)
                    {
                        this._isEditable = 1;
                    }
                    else
                    {
                        this._isEditable = 2;
                    }
                }
                return (this._isEditable == 1);
            }
        }

        public string LocalResourceFile
        {
            get
            {
                if (this._localResourceFile == "")
                {
                    return (this.TemplateSourceDirectory + "/App_LocalResources/" + this.ID);
                }
                return this._localResourceFile;
            }
            set
            {
                this._localResourceFile = value;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ModuleInfo ModuleConfiguration
        {
            get
            {
                return this._moduleConfiguration;
            }
            set
            {
                this._moduleConfiguration = value;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public int ModuleId
        {
            get
            {
                if (this._moduleConfiguration != null)
                {
                    return Convert.ToInt32(this._moduleConfiguration.ModuleID);
                }
                return Null.NullInteger;
            }
        }

        public string ModulePath
        {
            get
            {
                return (this.TemplateSourceDirectory + "/");
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public PortalAliasInfo PortalAlias
        {
            get
            {
                return this.PortalSettings.PortalAlias;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int PortalId
        {
            get
            {
                return this.PortalSettings.PortalId;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DotNetNuke.Entities.Portals.PortalSettings PortalSettings
        {
            get
            {
                return PortalController.GetCurrentPortalSettings();
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public Hashtable Settings
        {
            get
            {
                if (this._settings == null)
                {
                    this._settings = DotNetNuke.Entities.Portals.PortalSettings.GetModuleSettings(this.ModuleId);
                    this._settings = DotNetNuke.Entities.Portals.PortalSettings.GetTabModuleSettings(this.TabModuleId, this._settings);
                }
                return this._settings;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
        public int TabId
        {
            get
            {
                if (this._moduleConfiguration != null)
                {
                    return Convert.ToInt32(this._moduleConfiguration.TabID);
                }
                return Null.NullInteger;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int TabModuleId
        {
            get
            {
                if (this._moduleConfiguration != null)
                {
                    return Convert.ToInt32(this._moduleConfiguration.TabModuleID);
                }
                return Null.NullInteger;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int UserId
        {
            get
            {
                if (HttpContext.Current.Request.IsAuthenticated)
                {
                    return this.UserInfo.UserID;
                }
                return -1;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public DotNetNuke.Entities.Users.UserInfo UserInfo
        {
            get
            {
                return UserController.GetCurrentUserInfo();
            }
        }
    }
}

